import { useEffect, useMemo, useState } from 'react' import { AxiosResponse, CreateAxiosDefaults } from 'axios' import { addQueryArgs } from '@wordpress/url' import { ExportSnippets } from '../../types/ExportSnippets' import { Snippet } from '../../types/Snippet' import { isNetworkAdmin } from '../general' import { useAxios } from './axios' import { encodeSnippetCode } from '../snippets' const ROUTE_BASE = window.CODE_SNIPPETS?.restAPI.snippets const AXIOS_CONFIG: CreateAxiosDefaults = { headers: { 'X-WP-Nonce': window.CODE_SNIPPETS?.restAPI.nonce } } export interface Snippets { fetchAll: (network?: boolean | null) => Promise> fetch: (snippetId: number, network?: boolean | null) => Promise> create: (snippet: Snippet) => Promise> update: (snippet: Snippet) => Promise> delete: (snippet: Snippet) => Promise> activate: (snippet: Snippet) => Promise> deactivate: (snippet: Snippet) => Promise> export: (snippet: Snippet) => Promise> exportCode: (snippet: Snippet) => Promise> } const buildURL = ({ id, network }: Snippet, action?: string) => addQueryArgs( [ROUTE_BASE, id, action].filter(Boolean).join('/'), { network: network ? true : undefined } ) export const useSnippetsAPI = (): Snippets => { const { get, post, del } = useAxios(AXIOS_CONFIG) return useMemo((): Snippets => ({ fetchAll: network => get(addQueryArgs(ROUTE_BASE, { network })), fetch: (snippetId, network) => get(addQueryArgs(`${ROUTE_BASE}/${snippetId}`, { network })), create: snippet => post(`${ROUTE_BASE}`, encodeSnippetCode(snippet)), update: snippet => post(buildURL(snippet), encodeSnippetCode(snippet)), delete: (snippet: Snippet) => del(buildURL(snippet)), activate: snippet => post(buildURL(snippet, 'activate')), deactivate: snippet => post(buildURL(snippet, 'deactivate')), export: snippet => get(buildURL(snippet, 'export')), exportCode: snippet => get(buildURL(snippet, 'export-code')) }), [get, post, del]) } export const useSnippets = (): Snippet[] | undefined => { const api = useSnippetsAPI() const [snippets, setSnippets] = useState() useEffect(() => { if (!snippets) { api.fetchAll(isNetworkAdmin()) .then(response => setSnippets(response.data)) } }, [api, snippets]) return snippets }